package com.qf.route;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        //rabbitmq服务器安装的机器IP
        factory.setHost("localhost");
        //rabbitmq通过amqp协议连接时的端口号
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        //设置消息数据保存的虚拟主机,不同的虚拟主机彼此隔离
        factory.setVirtualHost("cdm");

        //获取connection对象
        Connection connection = factory.newConnection();
        //通过connection获取内部通道
        Channel channel = connection.createChannel();

        //声明交换机
        /*
            路由模式要求精确路由键，所以交换机类型是：DIRECT
         */
        channel.exchangeDeclare("routeEx", BuiltinExchangeType.DIRECT);

        //声明2个队列
        channel.queueDeclare("routeQue1",true,false,false,null);
        channel.queueDeclare("routeQue2",true,false,false,null);

        //绑定交换机和队列的关系
        /*
            String queue: 队列名
            String exchange：交换机名
            String routingKey：路由键  DIRECT类型的交换机，需要指定精确路由键
         */
        channel.queueBind("routeQue1","routeEx","A");
        channel.queueBind("routeQue2","routeEx","B");

        //发送消息
        channel.basicPublish("routeEx","A",null,("我是rabbitmq发送的路由消息消息，路由键为A").getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("routeEx","B",null,("我是rabbitmq发送的路由消息消息，路由键为B").getBytes(StandardCharsets.UTF_8));
        channel.basicPublish("routeEx","C",null,("我是rabbitmq发送的路由消息消息，路由键为C").getBytes(StandardCharsets.UTF_8));

        //释放资源
        channel.close();
        connection.close();
    }
}
